package com.chase.springboot.service.impl;

import com.chase.springboot.mapper.MenuMapper;
import com.chase.springboot.mapper.RoleMapper;
import com.chase.springboot.mapper.RoleMenuMapper;
import com.chase.springboot.model.Menu;
import com.chase.springboot.model.Role;
import com.chase.springboot.model.RoleMenu;
import com.chase.springboot.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Menu> getMenusByRoleId(Integer id) {
        //拿到菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectMenuIdsByRoleId(id);
        if (menuIds == null || menuIds.size() == 0) return null;
        //查出对应的菜单信息
        return menuMapper.selectByMenuIds(menuIds);
    }

    @Override
    public boolean addMenuToRole(Integer menuId, Integer roleId) {
        //此处需要先判断menuId，roleId是否有效
        Menu menu = menuMapper.selectByPrimaryKey(menuId);
        if (menu == null) return false;
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role == null) return false;
        //添加关联
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setMenuId(menuId);
        roleMenu.setRoleId(roleId);
        int i = roleMenuMapper.insert(roleMenu);
        return i > 0;
    }

    @Override
    public boolean deleteMenuInRole(Integer roleId) {
        int i = roleMenuMapper.deleteByRoleId(roleId);
        return i > 0;
    }
}
